function catpath = catmats(matpath,catdim_char)
%Thomas Stevens - Lim Lab. Opened 012413
% Cat 2 cell array mat files along specified dimension
% - because ND arrays are slow to read/write/process if not operating on all dims
%INPUT: cell array of matfile paths, in order of concatenation,
%       dimension to use: 'x','y','z','t','c','p'
%OUTPUT: path to a new matfile containing the concatenation
% e.g.
% matpath{1} = '/Users/ucsf/Desktop/Lim/All_Lim_Microscopy/Yeast/011513_yTS27g-39_growth_t4.mat';
% matpath{2} = '/Users/ucsf/Desktop/Lim/All_Lim_Microscopy/Yeast/011513_yTS27g-39_growth_t4.mat';

dimstr = 'xyztc';
catdim_num = find(catdim_char==dimstr);
timestr = 'tcp';
catdim_num_t = find(catdim_char==timestr);

catpath = [matpath{1}(1:strfind(matpath{1},'.mat')-1) '_cat.mat'];
catfile = matfile(catpath,'Writable',true);

for i=1:length(matpath)
    m{i} = matfile(matpath{i});
    w{i} = who('-file',matpath{i});
    if i==1
        ixns = w{i};
    else
        ixns = intersect(ixns,w{i});
    end
    s = m{i}.s;
    cellsize(i,:) = [s.x s.y s.z s.time s.channels s.positions];
end

if ismember('I',ixns)
    if catdim_char=='p'
        %todo
        catfile.I = cell(sum(cellsize(:,6)),1);
    elseif catdim_num > 0
        catfile.I = cell(cellsize(1,6),1);
        sizecat = cellsize(1,1:5);
        sizecat(1,catdim_num) = sum(cellsize(:,catdim_num));
        for p=1:cellsize(1,6)
            disp(['Joining on interior dimension ' catdim_char ', p=' num2str(p)]) 
            tic
            %catfile.I(p,1) = zeros(sizecat,'uint16');
            catfile.I(p,1) = { cat( catdim_num, cell2mat(m{1}.I(p,1)), ...
                cell2mat(m{2}.I(p,1)) ) };
            toc
        end
        
        %Cat time_v and s.time
        if catdim_char=='t'
            catfile_s = m{1}.s;
            catfile_s.time = sum(cellsize(:,catdim_num));
            catfile.s = catfile_s;
            endpt = m{1}.time_v;
            startpt = m{2}.time_v;
            endpt = repmat(endpt(end,:,:),[size(startpt,1) 1 1]);
            catfile.time_v = cat(catdim_num_t,endpt, ...
                startpt + endpt);
        end
    else
        
    end
    
end
end